package com.app.couponsharelife.ui.main.home.search
import android.content.Intent
import android.view.LayoutInflater
import android.view.View
import android.view.WindowManager
import android.view.inputmethod.EditorInfo
import android.widget.LinearLayout
import android.widget.TextView
import com.google.gson.Gson
import com.app.couponsharelife.R
import com.app.couponsharelife.base.BaseActivity
import com.app.couponsharelife.data.bean.RemoteResultBean
import com.app.couponsharelife.data.bean.SearchHistoryBean
import com.app.couponsharelife.data.remote.retrofit.RetrofitWorker
import com.app.couponsharelife.data.remote.retrofit.exception.OtherException
import com.app.couponsharelife.utils.AppUtils
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.observers.DisposableObserver
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.activity_searchselecte.*
import kotlinx.android.synthetic.main.base_title_search_white.*
import java.util.HashMap

/**
 *Created by xct on 2019/1/9
 *Description:搜索标签页面
 */
class SearchSelecteActivity:BaseActivity() {
    private var lifeHotKeyList= arrayListOf<String>()
    private var goodsHotKeyList= arrayListOf<String>()
    private var historyList= arrayListOf<String>()
    private var isFirst=true
    private var type=0
    private var goodsType=""
    override val viewLayoutId: Int
        get() = R.layout.activity_searchselecte

    override fun initViews() {
        AppUtils.initImmersionBar(this,true)
        window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE)
        type=intent.getIntExtra("Type",0)
        goodsType=intent.getStringExtra("GoodsType")?:"TB"
        when(type){
            0->{
                when(goodsType){
                    "TB"->{
                        basetitle_edit.hint="搜索你感兴趣的商品"
                    }
                    "PDD"->{
                        basetitle_edit.hint="粘贴或输入拼多多宝贝标题"
                    }
                    "JD"->{
                        basetitle_edit.hint="粘贴或输入京东宝贝标题"
                    }
                    else->{
                        basetitle_edit.hint="搜索你感兴趣的商品"
                    }
                }
                getGoodsHotKey()
            }
            1->{
                basetitle_edit.hint="搜所你感兴趣的商家"
                getLifeHotKey()
            }
            else->{
                basetitle_edit.hint="搜索你感兴趣的商品"
                getGoodsHotKey()
            }
        }
        initHistoryFlowLayout(type)
        basetitle_llclose.setOnClickListener {
            AppUtils.hideInputBoard(this,basetitle_edit)
            finish()
        }
        basetitle_tvZW.post {
            val layoutparams=basetitle_tvZW.layoutParams as LinearLayout.LayoutParams
            layoutparams.width=AppUtils.getDisplayMetrics(this).widthPixels
            layoutparams.height=AppUtils.getStatusBarHeight(this)
            basetitle_tvZW.layoutParams=layoutparams
        }
        searchselecte_imag_delete.setOnClickListener {
            if (0==type){
                AppUtils.setString("searchKey","")
            }else if (1==type){
                AppUtils.setString("searchHistory","")
            }
            initHistoryFlowLayout(type)
        }
        basetitle_edit.setOnEditorActionListener { _, actionId, _ ->
            if (actionId == EditorInfo.IME_ACTION_SEARCH){
                val keyWord=basetitle_edit.text.toString().trim()
                if (keyWord.isNotEmpty()){
                    setKey(keyWord)
                    setIntent(keyWord)
                }else{
                    showToastMsg("请输入搜索内容！")
                }
                true
            }else{
                false
            }
        }
        basetitle_imag_delete.setOnClickListener {
            basetitle_edit.setText("")
        }
    }
    private fun initFlowLayout(type:Int) {
        val hotList=if (type==0){
            goodsHotKeyList
        }else{
            lifeHotKeyList
        }
        searchselecte_hotfl.removeAllViews()
        val inflater = LayoutInflater.from(this)
        for (hot in hotList) {
            val view = inflater.inflate(R.layout.hot_search_item, searchselecte_hotfl, false) as TextView
            view.text = hot
            searchselecte_hotfl.addView(view)
        }
        searchselecte_hotfl.setListener { position, view ->
            val keyWord = hotList[position]
            if (!historyList.contains(keyWord)){
                if (historyList.size>=10){
                    historyList.removeAt(9)
                    historyList.add(0,keyWord)
                }else{
                    historyList.add(0,keyWord)
                }
            }
            setKey(keyWord)
            setIntent(keyWord)
        }
        searchselecte_hotfl.visibility = View.VISIBLE
    }
    private fun initHistoryFlowLayout(type:Int) {
        val keys=if (type==0){
            AppUtils.getString("searchKey", "")
        }else{
            AppUtils.getString("searchHistory", "")
        }
        if (keys.isNotEmpty()){
            historyList.clear()
            historyList.addAll(Gson().fromJson(keys, SearchHistoryBean::class.java).list)
            searchselecte_oldfl.removeAllViews()
            val inflater = LayoutInflater.from(this)
            for (hot in historyList) {
                val view = inflater.inflate(R.layout.hot_search_item, searchselecte_oldfl, false) as TextView
                view.text = hot
                searchselecte_oldfl.addView(view)
            }
            searchselecte_oldfl.setListener { position, view ->
                val keyWord = historyList[position]
                if (type==0){
                    val intent=when(goodsType){
                        "JD"->{
                            Intent(this,JDSearchGoodsListActivity::class.java)
                        }
                        else->{
                            Intent(this,HomeSearchActivity::class.java)
                        }
                    }
                    intent.putExtra("KeyWord",keyWord)
                    intent.putExtra("SearchType",goodsType)
                    startActivity(intent)
                }else{
                    val intent=Intent(this,LifeSearchResultActivity::class.java)
                    intent.putExtra("KeyWord",keyWord)
                    startActivity(intent)
                }
            }
            searchselecte_oldfl.visibility = View.VISIBLE
        }else{
            searchselecte_oldfl.visibility = View.GONE
        }
    }
    private fun setKey(keyWord:String){
        if (!historyList.contains(keyWord)){
            if (historyList.size>=10){
                historyList.removeAt(9)
                historyList.add(0,keyWord)
            }else{
                historyList.add(0,keyWord)
            }
        }
        if (type==0){
            AppUtils.setString("searchKey", Gson().toJson(SearchHistoryBean(historyList)))
        }else if(type==1){
            AppUtils.setString("searchHistory", Gson().toJson(SearchHistoryBean(historyList)))
        }
    }
    private fun setIntent(keyWord:String){
        if (type==0){
            val intent=when(goodsType){
                "JD"->{
                    Intent(this,JDSearchGoodsListActivity::class.java)
                }
                else->{
                    Intent(this,HomeSearchActivity::class.java)
                }
            }
            intent.putExtra("KeyWord",keyWord)
            intent.putExtra("SearchType",goodsType)
            startActivity(intent)
        }else{
            val intent=Intent(this,LifeSearchResultActivity::class.java)
            intent.putExtra("KeyWord",keyWord)
            startActivity(intent)
        }
    }
    private fun getLifeHotKey(){
        val map= HashMap<String,String>()
        map["num"]="10"
        RetrofitWorker.retrofitWorker.getLifeHotKey(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(object :DisposableObserver<RemoteResultBean<List<String>>>(){
                    override fun onComplete() {

                    }

                    override fun onNext(it: RemoteResultBean<List<String>>) {
                        if (it.code==200){
                            if (it.data!!.isNotEmpty()){
                                lifeHotKeyList.clear()
                                lifeHotKeyList.addAll(it.data!!)
                                initFlowLayout(1)
                            }
                        }
                    }

                    override fun onError(e: Throwable) {
                        if (e is OtherException){
                            showToastMsg(e.msg)
                        }else{
                            showToastMsg("网络加载出错了！")
                        }
                    }

                })
    }
    private fun getGoodsHotKey(){
        val map= HashMap<String,String>()
        map["num"]="10"
        RetrofitWorker.retrofitWorker.getHotKeyword(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(object :DisposableObserver<RemoteResultBean<List<String>>>(){
                    override fun onComplete() {

                    }

                    override fun onNext(it: RemoteResultBean<List<String>>) {
                        if (it.code==200){
                            if (it.data!!.isNotEmpty()){
                                goodsHotKeyList.clear()
                                goodsHotKeyList.addAll(it.data!!)
                                initFlowLayout(0)
                            }
                        }
                    }

                    override fun onError(e: Throwable) {
                        if (e is OtherException){
                            showToastMsg(e.msg)
                        }else{
                            showToastMsg("网络加载出错了！")
                        }
                    }

                })
    }

    override fun onResume() {
        super.onResume()
        if (!isFirst){
            initHistoryFlowLayout(type)
        }
        isFirst=false
    }
    override fun onDestroy() {
        super.onDestroy()
        AppUtils.destroyImmersionBar(this)
    }
}